package com.github.icloudpay.crm.core.biz;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.msg.SmsType;

@Service
public class SmsGateWayBiz {
	private static final Logger logger = LoggerFactory.getLogger(SmsGateWayBiz.class);

	@Value("${bountyHunter.smsCodeTime}")
	private int smsCodeTime;
    @Autowired
    private RedisTemplate redisTemplate;
	//产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";
    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAImVws8vSV9l6p";
    static final String accessKeySecret = "u4ktUQEEwHJ3aC1fshPXhVJY6jn8FW";
	
	/**
	 * 参数说明
	 * @author centerroot
	 * @time 创建时间:2018年5月21日下午5:50:04
	 * @param param
	 * @return
	 */
	public Map<String, Object> sendCode(Map<String, Object> param) {
		logger.info("发送短信验证码请求参数  request{}", param);
		Map<String, Object> respMap = new HashMap<String, Object>();
		Map<String, Object> restParam = new HashMap<String, Object>();
		restParam.putAll(param);
		String code = this.getCode();
		String phone = (String) param.get("phone");
		redisTemplate.opsForValue().set("SMS_CODE_KEY:" + phone, code, smsCodeTime);
		logger.info("发送短信验证码,code:{}", code);
		restParam.put("code", code);
		try {
			logger.info("发送短信验证码请求参数 【第一次请求参数】 restParam{}", restParam);
			SendSmsResponse sendSmsFirstResponse = sendSms(restParam);
			logger.info("发送短信验证码响应结果【第一次请求结果】,sendSmsResponse=={}", sendSmsFirstResponse.toString());
			if (sendSmsFirstResponse != null && sendSmsFirstResponse.getCode() != null) {
				if (sendSmsFirstResponse.getCode().equals("OK")) {
					respMap.put("code", ResponseCode.OK.getCode());
					respMap.put("msg", ResponseCode.OK.getMessage());
				} else if (sendSmsFirstResponse.getCode().equals("isp.SYSTEM_ERROR")) {
					logger.info("发送短信验证码请求参数 【第二次请求参数-1】 restParam{}", restParam);
					SendSmsResponse sendSmsSecondResponse = sendSms(restParam);
					logger.info("发送短信验证码响应结果【第二次请求结果-1】,sendSmsResponse=={}", sendSmsFirstResponse.toString());
					if (sendSmsSecondResponse != null && sendSmsSecondResponse.getCode() != null && sendSmsSecondResponse.getCode().equals("OK")) {
						respMap.put("code", ResponseCode.OK.getCode());
						respMap.put("msg", ResponseCode.OK.getMessage());
					}else{
						respMap.put("code", ResponseCode.SMS_SEND_FAIL.getCode());
						respMap.put("msg", ResponseCode.SMS_SEND_FAIL.getMessage());
					}
				}else{
					respMap.put("code", ResponseCode.SMS_SEND_FAIL.getCode());
					respMap.put("msg", ResponseCode.SMS_SEND_FAIL.getMessage());
				}
				
			}else{
				logger.info("发送短信验证码请求参数 【第二次请求参数-2】 restParam{}", restParam);
				SendSmsResponse sendSmsSecondResponse = sendSms(restParam);
				logger.info("发送短信验证码响应结果【第二次请求结果-2】,sendSmsResponse=={}", sendSmsSecondResponse.toString());
				if (sendSmsSecondResponse != null && sendSmsSecondResponse.getCode() != null && sendSmsSecondResponse.getCode().equals("OK")) {
					respMap.put("code", ResponseCode.OK.getCode());
					respMap.put("msg", ResponseCode.OK.getMessage());
				}else{
					respMap.put("code", ResponseCode.SMS_SEND_FAIL.getCode());
					respMap.put("msg", ResponseCode.SMS_SEND_FAIL.getMessage());
				}
			}
			
		} catch (com.aliyuncs.exceptions.ClientException e1) {
			respMap.put("code", ResponseCode.SMS_SEND_FAIL.getCode());
			respMap.put("msg", ResponseCode.SMS_SEND_FAIL.getMessage());
			e1.printStackTrace();
		}

		logger.info("发送短信验证码响应结果：{}", respMap);
		return respMap;
	}

	/**
	 * 验证短信验证码
	 */
	public Map<String, Object> verificationCode(Map<String, Object> param) {
		logger.info("验证短信验证码------请求参数:{}", param);
		String phone = (String) param.get("phone");
		String code = (String) param.get("code");
		Map<String, Object> respMap = new HashMap<String, Object>();
		
		boolean flag = false;
		String smsCode=String.valueOf(redisTemplate.opsForValue().get("SMS_CODE_KEY:" + phone));
		logger.info("系统发送过的短信验证码------code:{}", smsCode);
		if (code.equals(smsCode)) {
			flag = true;
		}
		
		respMap.put("verifyStatus", flag);
		respMap.put("code", ResponseCode.OK.getCode());
		respMap.put("msg", ResponseCode.OK.getMessage());
		
		logger.info("验证短信验证码------结果:{}", flag);
		return respMap;
	}

	private String getCode() {
		String[] beforeShuffle = new String[] { "1", "0", "2", "3", "4", "5", "6", "7", "8", "9" };
		List list = Arrays.asList(beforeShuffle);
		Collections.shuffle(list);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i));
		}
		String afterShuffle = sb.toString();
		String result = afterShuffle.substring(3, 9);
		return result;
	}



	
	public SendSmsResponse sendSms(Map<String, Object> param) throws com.aliyuncs.exceptions.ClientException {

		logger.info("发送短信验证码请求参数,param=={}", param);
		String code = (String) param.get("code");
		String phone = (String) param.get("phone");
		String smsType = (String) param.get("smsType");
		
		//可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("潍坊市云支付");
        
        
        //必填:短信模板-可在短信控制台中找到
//        request.setTemplateCode("SMS_1000000");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//        request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
        if (SmsType.register.getCode().equals(smsType)) {
        	request.setTemplateCode("SMS_85555075");
        	request.setTemplateParam("{\"code\":\""+code+"\"}");
		} else if (SmsType.changeMobile.getCode().equals(smsType)) {
			request.setTemplateCode("SMS_85410076");
        	request.setTemplateParam("{\"code\":\""+code+"\"}");
		}
        
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//        request.setOutId("yourOutId");

        //hint 此处可能会抛出异常，注意catch
		SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
		logger.info("发送短信验证码响应结果,sendSmsResponse=={}", sendSmsResponse.toString());
        return sendSmsResponse;
    }


    public static QuerySendDetailsResponse querySendDetails(String bizId) throws com.aliyuncs.exceptions.ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber("15205442200");
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }
	

}
